package com.yogee.topseller.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.login.model.bean.CheckBean;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.fragment.product.model.bean.ProductBean;
import com.yogee.topseller.fragment.product.model.bean.ProductListBean;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ProductCompareActivity extends HttpActivity {

    Unbinder unbinder;
    @BindView(R.id.title_white_left_back)
    LinearLayout titleWhiteLeftBack;
    @BindView(R.id.title_white_left_txt)
    TextView titleWhiteLeftTxt;
    @BindView(R.id.title_white_title)
    TextView titleWhiteTitle;
    @BindView(R.id.title_white_right_txt)
    TextView titleWhiteRightTxt;
    @BindView(R.id.product_list)
    LinearLayout productList;
    @BindView(R.id.tv_compare_btn)
    TextView tvCompareBtn;
    @BindView(R.id.title_white_right_add_img)
    ImageView titleWhiteRightAddImg;
    @BindView(R.id.activity_product_compare)
    LinearLayout activityProductCompare;
    @BindView(R.id.iv_compare_delete)
    ImageView ivCompareDelete;
    @BindView(R.id.btn_submit)
    LinearLayout btnSubmit;
    @BindView(R.id.img_nodata)
    ImageView img_nodata;

    private String selectProductId;
    private List<SelectProduct> productBeanList;
    private int selectNum = 0;//已选产品数量

    class SelectProduct {
        public boolean isSelect;
        public ProductBean productBean;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_product_compare;
    }

    @Override
    protected void initView() {
        productBeanList = new ArrayList<>();
        titleWhiteLeftBack.setVisibility(View.VISIBLE);
        titleWhiteTitle.setText("产品对比");
        titleWhiteRightTxt.setText("编辑");
        titleWhiteRightTxt.setVisibility(View.VISIBLE);
        titleWhiteRightAddImg.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadCompareData();
    }

    /**
     * 获取对比产品列表
     */
    private void loadCompareData() {
        productList.removeAllViews();
        HttpManager.getInstance().loadCompareProducts(AppUtil.getUserId(this)).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ProductListBean>() {
            @Override
            public void onNext(ProductListBean o) {
                if ("1".equals(o.getResult())) {
                    if (null != o.getProductList() && o.getProductList().size() > 0) {
                        img_nodata.setVisibility(View.GONE);
                        addCompareList(o.getProductList());
                    }else{
                        img_nodata.setVisibility(View.VISIBLE);
                    }
                }
            }
        }, this));
    }

    /**
     * 添加布局数据
     */
    private void addCompareList(List<ProductBean> productUnselect) {
        productList.removeAllViews();
        productBeanList.clear();
        for (int i = 0; i < productUnselect.size(); i++) {
            final int tempNum = i;
            SelectProduct selectProduct = new SelectProduct();
            selectProduct.isSelect = false;
            selectProduct.productBean = productUnselect.get(i);
            productBeanList.add(selectProduct);
            View childView = LayoutInflater.from(ProductCompareActivity.this).inflate(R.layout.item_product_compare, null);
            final ImageView isCheckIv = (ImageView) childView.findViewById(R.id.cb_select);
            LinearLayout selectLl = (LinearLayout) childView.findViewById(R.id.select_ll);

            selectLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (productBeanList.get(tempNum).isSelect) {
                        productBeanList.get(tempNum).isSelect = false;
                        isCheckIv.setImageResource(R.drawable.unselect1);
                    } else {
                        productBeanList.get(tempNum).isSelect = true;
                        isCheckIv.setImageResource(R.drawable.select1);
                    }
                }
            });
            TextView nameTv = (TextView) childView.findViewById(R.id.tv_product_name);
            nameTv.setText(productUnselect.get(i).getName());
            TextView item_product_compare_type_tv = (TextView) childView.findViewById(R.id.item_product_compare_type_tv);
            item_product_compare_type_tv.setText(productUnselect.get(i).getProType());
            productList.addView(childView);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.img_product_compare,R.id.title_white_left_back, R.id.title_white_left_txt, R.id.title_white_right_txt, R.id.title_white_right_add_img, R.id.btn_submit, R.id.ll_confrim_layout, R.id.tv_compare_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.img_product_compare:
//                ToastUtils.showToast(ProductCompareActivity.this,"搜索");
//                Intent intent = new Intent();
//                intent.setClass(ProductCompareActivity.this,SearchAndSelectActivity.class);
//                startActivity(intent);
                startActivity(new Intent(ProductCompareActivity.this, CompareProductActivity.class).putExtra("type", "0"));
                break;
            case R.id.title_white_left_back:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
                finish();
                break;
            case R.id.title_white_left_txt:
                //编辑状态取消按钮事件
                titleWhiteLeftBack.setVisibility(View.VISIBLE);
//                titleWhiteRightAddImg.setVisibility(View.VISIBLE);
                titleWhiteLeftTxt.setText("");
                titleWhiteLeftTxt.setVisibility(View.GONE);
                titleWhiteRightTxt.setText("编辑");
                tvCompareBtn.setText("开始对比");
                ivCompareDelete.setVisibility(View.GONE);
                break;
            case R.id.title_white_right_txt:
                if ("编辑".equals(titleWhiteRightTxt.getText().toString())) {
                    //打开编辑状态
//                    titleWhiteRightAddImg.setVisibility(View.GONE);
                    titleWhiteLeftBack.setVisibility(View.GONE);
                    titleWhiteLeftTxt.setText("取消");
                    titleWhiteLeftTxt.setVisibility(View.VISIBLE);
                    titleWhiteRightTxt.setText("全选");
                    tvCompareBtn.setText("删除");
                    ivCompareDelete.setVisibility(View.VISIBLE);
                    noSelect();
                } else if ("全选".equals(titleWhiteRightTxt.getText().toString())) {
                    selectAll();
                    titleWhiteRightTxt.setText("取消全选");
                } else if ("取消全选".equals(titleWhiteRightTxt.getText().toString())) {
                    noSelect();
                    titleWhiteRightTxt.setText("全选");
                }
                break;
            case R.id.title_white_right_add_img:
                //产品添加对比的 " + "
                startActivity(new Intent(this, CompareProductActivity.class).putExtra("type", "0").putExtra("id", AppUtil.getUserId(this)));
                break;
            case R.id.ll_confrim_layout:
                if (tvCompareBtn.getText().toString().equals("开始对比")) {
                    if (TextUtils.isEmpty(selectProductIdM())) {
                        ToastUtils.showToast(ProductCompareActivity.this, "请选择产品");
                        return;
                    }
                    if (selectNum < 2){
                        selectNum = 0;
                        ToastUtils.showToast(ProductCompareActivity.this, "请至少选择两款产品");
                        return;
                    }else if (selectNum >3){
                        selectNum = 0;
                        ToastUtils.showToast(ProductCompareActivity.this, "最多能选择三款产品");
                        return;
                    }else{
                        startCompareProduct();
                    }
                } else if (tvCompareBtn.getText().toString().equals("删除")) {
                    deleteCompareProduct();
                }
                break;
            case R.id.tv_compare_btn:
                if (tvCompareBtn.getText().toString().equals("开始对比")) {
                    if (TextUtils.isEmpty(selectProductIdM())) {
                        ToastUtils.showToast(ProductCompareActivity.this, "请选择产品");
                        return;
                    }
                    if (selectNum < 2){
                        selectNum = 0;
                        ToastUtils.showToast(ProductCompareActivity.this, "请至少选择两款产品");
                        return;
                    }else if (selectNum >3){
                        selectNum = 0;
                        ToastUtils.showToast(ProductCompareActivity.this, "最多能选择三款产品");
                        return;
                    }else{
                        startCompareProduct();
                    }
                } else if (tvCompareBtn.getText().toString().equals("删除")) {
                    deleteCompareProduct();
                }
                break;
        }
    }

    /**
     * 刷新页面
     */
    private void refreshView() {
        productList.removeAllViews();
        for (int i = 0; i < productBeanList.size(); i++) {
            final int tempNum = i;
            View childView = LayoutInflater.from(ProductCompareActivity.this).inflate(R.layout.item_product_compare, null);
            LinearLayout selectLl = (LinearLayout) childView.findViewById(R.id.select_ll);
            final ImageView isCheckIv = (ImageView) childView.findViewById(R.id.cb_select);

            selectLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (productBeanList.get(tempNum).isSelect) {
                        productBeanList.get(tempNum).isSelect = false;
                        isCheckIv.setImageResource(R.drawable.unselect1);
                    } else {
                        productBeanList.get(tempNum).isSelect = true;
                        isCheckIv.setImageResource(R.drawable.select1);
                    }
                }
            });
            
            TextView nameTv = (TextView) childView.findViewById(R.id.tv_product_name);
            nameTv.setText(productBeanList.get(i).productBean.getName());
            if (productBeanList.get(tempNum).isSelect) {
                isCheckIv.setImageResource(R.drawable.select1);
            }

            TextView item_product_compare_type_tv = (TextView) childView.findViewById(R.id.item_product_compare_type_tv);
            item_product_compare_type_tv.setText(productBeanList.get(i).productBean.getProType());
            productList.addView(childView);
        }
    }

    /**
     * 全选方法
     */
    private void selectAll() {
        for (int i = 0; i < productBeanList.size(); i++) {
            productBeanList.get(i).isSelect = true;
        }
        refreshView();
    }

    private void noSelect() {
        for (int i = 0; i < productBeanList.size(); i++) {
            productBeanList.get(i).isSelect = false;
        }
        refreshView();
    }

    /**
     * 组合选中产品id
     *
     * @return
     */
    private String selectProductIdM() {
        int tempSelectNum = 0;
        selectProductId = "";
        for (int i = 0; i < productBeanList.size(); i++) {
            if (productBeanList.get(i).isSelect) {
                tempSelectNum ++;
                if (TextUtils.isEmpty(selectProductId)) {
                    selectProductId = productBeanList.get(i).productBean.getId();
                } else {
                    selectProductId += "," + productBeanList.get(i).productBean.getId();
                }
            }
        }
        selectNum = tempSelectNum;
        return selectProductId;
    }

    /**
     * 开始对比产品
     */
    private void startCompareProduct() {
        int num = 0;
        for (int i = 0; i < productBeanList.size(); i++) {
            if (productBeanList.get(i).isSelect) {
                num++;
            }
        }
        if (num > 3) {
            ToastUtils.showToast(ProductCompareActivity.this, "最多只能选择三个产品");
            return;
        }
        setChooseProId(AppUtil.getUserId(this), selectProductIdM(),num);
    }

    private void setChooseProId(String userId, String proId,final int num) {
        HttpManager.getInstance().setChooseProId(userId, proId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                if(num!=3)
                    startActivity(new Intent(ProductCompareActivity.this, CompareProductActivity.class).putExtra("num", num).putExtra("type", "1").putExtra("proId", selectProductIdM()));
                else
                    startActivity(new Intent(ProductCompareActivity.this, CompareProductActivity1.class).putExtra("num", num).putExtra("type", "1").putExtra("proId", selectProductIdM()));
            }
        }, this));
    }

    /**
     * 删除对比产品
     */
    private void deleteCompareProduct() {
        if (TextUtils.isEmpty(selectProductIdM())) {
            ToastUtils.showToast(ProductCompareActivity.this, "请选择产品");
            return;
        }
        HttpManager.getInstance().deleteCompareProduct(selectProductIdM(), AppUtil.getUserId(ProductCompareActivity.this)).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<CheckBean>() {
            @Override
            public void onNext(CheckBean o) {
                if ("1".equals(o.getResult())) {
                    productBeanList.clear();
                    loadCompareData();
                    ToastUtils.showToast(ProductCompareActivity.this,"删除成功");
                }
            }
        }, this));
    }

}
